package com.fram.service.admin.impl;

import java.util.Date;
import java.util.List;
import javax.transaction.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.fram.bean.admin.distributor.request.DistributorAdminUserAddRequest;
import com.fram.bean.admin.distributor.response.DistributorSearchResponse;
import com.fram.bean.api.project.request.CategoryRequest;
import com.fram.bean.api.project.response.CategoryResponse;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.ErrCode;
import com.fram.common.canstant.PublicConstant;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.PublicMethod;
import com.fram.common.util.qiniu.QiniuUtils;
import com.fram.entity.AdminUserRole;
import com.fram.entity.DistributorFarm;
import com.fram.entity.DistributorProjectCategory;
import com.fram.entity.ProjectCategory;
import com.fram.entity.ProjectGoods;
import com.fram.entity.User;
import com.fram.entity.UserLogin;
import com.fram.mapper.AdminUserRoleMapper;
import com.fram.mapper.DistributorFarmMapper;
import com.fram.mapper.DistributorProjectCategoryMapper;
import com.fram.mapper.ProjectCategoryMapper;
import com.fram.mapper.ProjectGoodsMapper;
import com.fram.mapper.UserLoginMapper;
import com.fram.mapper.UserMapper;
import com.fram.service.admin.DistributorService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class DistributorServiceImpl implements DistributorService {

	@Autowired
	private DistributorFarmMapper distributorFarmMapper;
	@Autowired
	private ProjectCategoryMapper projectCategoryMapper;
	@Autowired
	private DistributorProjectCategoryMapper distributorProjectCategoryMapper;
	@Autowired
	private UserLoginMapper userLoginMapper;
	@Autowired
	private AdminUserRoleMapper userRoleMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ProjectGoodsMapper projectGoodsMapper;
	@Autowired
	private QiniuUtils qiniuUtils;

	/** 后台-分销商列表 **/
	@Override
	public PageInfo<DistributorSearchResponse> list(PageBean<DistributorFarm> request) throws ProException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<DistributorSearchResponse> list = distributorFarmMapper.selectAll(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	/** 详情 **/
	@Override
	public DistributorFarm details(Long id) throws ProException {
		DistributorFarm request = distributorFarmMapper.selectByPrimaryKey(id);
		if (request == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return request;
	}

//	/** 分销商增加售卖的类型 **/
//	@Override
//	public void insertProjectCategory(Long distributorId, List<Long> categoryIds) throws ProException {
//		try {
//			for (Long id : categoryIds) {
//				DistributorProjectCategory record = new DistributorProjectCategory();
//				record.setDistributorId(distributorId);
//				record.setCategoryId(id);
//				distributorProjectCategoryMapper.insertSelective(record);
//			}
//		} catch (Exception e) {
//		}
//	}

	/** 新增 **/
	@Override
	public void add(DistributorFarm request) throws ProException {
		if (!StringUtils.isEmpty(request.getLogo())) {
			request.setLogo(qiniuUtils.uploadImageUrl(request.getLogo()));
		}
		if (!StringUtils.isEmpty(request.getBusinessLicense())) {
			request.setBusinessLicense(qiniuUtils.uploadImageUrl(request.getBusinessLicense()));
		}
		int in = distributorFarmMapper.insertSelective(request);
		if (in <= 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
	}

	/** 修改 **/
	@Override
	public void update(DistributorFarm request) throws ProException {
		if (!StringUtils.isEmpty(request.getLogo())) {
			request.setLogo(qiniuUtils.uploadImageUrl(request.getLogo()));
		}
		if (!StringUtils.isEmpty(request.getBusinessLicense())) {
			request.setBusinessLicense(qiniuUtils.uploadImageUrl(request.getBusinessLicense()));
		}
		int in = distributorFarmMapper.updateByPrimaryKeySelective(request);
		if (in <= 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
	}

	/** 展示 **/
	@Override
	public List<CategoryResponse> ListByFarmId(CategoryRequest request) throws ProException {
		List<CategoryResponse> list = distributorProjectCategoryMapper.selectProductCategoryList(request);
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	/** 增加一二 级类别 **/
	@Override
	public void addProjectCategroy(DistributorProjectCategory request) throws ProException {
		try {
			if (distributorProjectCategoryMapper.insertSelective(request) == 0) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
			}
		} catch (DataAccessException e) {
			throw new ProValiDataException(ErrCode.ERR_HAVE_EXISTED.getReturnCode(),
					ErrCode.ERR_HAVE_EXISTED.getReturnMsg());
		}
	}

	@Override
	@Transactional
	public void addDistributorAdminUser(DistributorAdminUserAddRequest request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getUserName()) || StringUtils.isEmpty(request.getPassWord())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		// 判断帐号是否存在 如果存在则修改密码
		UserLogin user = userLoginMapper.selectByUserName(request.getUserName());
		if (user == null) {// 不存在 则直接添加
			UserLogin login = new UserLogin();
			login.setLoginType(PublicConstant.LOGIN_TYPE_3);
			login.setUserId(request.getUserId());
			login.setCreateTime(new Date((System.currentTimeMillis() / 1000) * 1000));
			login.setAccount(request.getUserName());
			String vatePwd = PublicMethod.getMd5(request.getPassWord() + login.getCreateTime().getTime(), 1, true);
			login.setPassword(vatePwd);
			try {
				if (userLoginMapper.insertSelective(login) == 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "记录帐号密码失败");
				}
			} catch (DataAccessException e) {
				throw new ProRunTimeException(ErrCode.ERR_HAVE_EXISTED.getReturnCode(), ErrCode.ERR_HAVE_EXISTED.getReturnMsg());
			}
			if (request.getRoleId() != null) {
				AdminUserRole userRole = new AdminUserRole();
				userRole.setRoleId(request.getRoleId());
				userRole.setUserId(request.getUserId());
				if (userRoleMapper.insertSelective(userRole) == 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "记录角色失败");
				}
			}
		} else {// 存在 修改密码
			if (request.getUserId().longValue() != user.getUserId().longValue()) {
				throw new ProRunTimeException(ErrCode.ERR_HAVE_EXISTED.getReturnCode(), "帐号已经存在");
			}
			String vatePwd = PublicMethod.getMd5(request.getPassWord() + user.getCreateTime().getTime(), 1, true);
			user.setPassword(vatePwd);
			if (userLoginMapper.updateByPrimaryKeySelective(user) == 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "记录帐号密码失败");
			}
		}
		User u = new User();
		u.setId(request.getUserId());
		u.setUserType(PublicConstant.USER_TYPE_2);
		if (userMapper.updateByPrimaryKeySelective(u) <= 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "改变帐号类型失败");
		}
	}

	@Override
	public List<ProjectGoods> deleteProjectCategroy(Long id,Long distributorId) throws ProAffairException {
		DistributorProjectCategory discate = distributorProjectCategoryMapper.selectByPrimaryKey(id);
		ProjectCategory cate = projectCategoryMapper.selectByPrimaryKey(discate.getCategoryId());
		if(cate.getLevel()==1 && cate.getParentId()==0) {
			//可以查多个商品
			List<ProjectCategory> cateList = projectCategoryMapper.selectByParentId(cate.getId());
			
			for (ProjectCategory Category : cateList) {
				
				List<ProjectGoods> goods =projectGoodsMapper.selectByCategoryId(Category.getId(),distributorId);
				System.out.println("Category.getId()"+Category.getId());
				if(goods == null || goods.size()==0) {
					//删除改父级的子级和本身 先删子级 后删 父级
					if(distributorProjectCategoryMapper.deleteByPrimaryKey(id) <= 0 && distributorProjectCategoryMapper.deleteByCategory(Category.getId(),distributorId) <= 0) {
						throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
					}
				}else {
					return goods;
				}
			}
		} else {
			List<ProjectGoods> goods =projectGoodsMapper.selectByCategoryId(cate.getId(),distributorId);
			if(goods == null || goods.size()==0) {
				if(distributorProjectCategoryMapper.deleteByPrimaryKey(id) <= 0){
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
				}
			}else {
				return goods;
			}
		}
		return null;
	}

	@Override
	public PageInfo<DistributorFarm> withChildren(PageBean<DistributorFarm> request) throws ProException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<DistributorFarm> list = distributorFarmMapper.withChildren(request.getParam());
		if(list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}
}
